const timeUtil = {
  formatDateToStr: function(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    const minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    return year + "-" + month + "-" + day + " " + hour + ":" + minute;
  },

  // 后端字符串转日期对象 ""2021-07-27T21:02:55.000+00:00""
  DateStrToDate: function(dateStr = "") {
    // 提取日期字符串
    var pattern = /[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}/
    var dateTimeStr = dateStr.match(pattern)[0];
    // 以T为分隔分别提取出年月日和时分秒
    var timeStrArray = dateTimeStr.split("T");
    var dateStr = timeStrArray[0];
    var timeStr = timeStrArray[1];

    // 提取年月日
    var dateArray = dateStr.split("-");
    var year = parseInt(dateArray[0], 10);
    var month = parseInt(dateArray[1], 10) - 1;
    var day = parseInt(dateArray[2], 10);
    
    // 提取时分秒
    var timeArray = timeStr.split(":");
    var hour = parseInt(timeArray[0], 10);
    var minute = parseInt(timeArray[1], 10);
    var second = parseInt(timeArray[2], 10);

    var date = new Date(year, month, day, hour, minute, second);
    return date;
  },

  // 解决小程序后端时间时区问题
  toLocalDate: function(date = new Date()) {
    return new Date(date.getTime() + date.getTimezoneOffset() * 60000);
  },
}

module.exports = {
  timeUtil
}